package com.turing.cloud.handler;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description feign调用token携带
 * @Author lcy
 * @Date 2021/6/9 10:31
 */
@Configuration
public class TokenRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            // 获取该次请求得token 将token传递
            if (requestAttributes != null) {
                HttpServletRequest request = requestAttributes.getRequest();
                String token = request.getHeader("tokenStr");
                if (StringUtils.isNotBlank(token)) {
                    requestTemplate.header("tokenStr", token);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
